package com.learn.eduuserboot.controller;

import com.alibaba.fastjson.JSON;
import com.learn.eduapi.entity.ResponseDTO;
import com.learn.eduapi.entity.user.User;
import com.learn.eduapi.entity.weixin.Token;
import com.learn.eduapi.entity.weixin.UserDTO;
import com.learn.eduapi.entity.weixin.WxUser;
import com.learn.eduuserboot.service.UserService;
import com.learn.eduuserboot.until.HttpClientUtil;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 微信登录80
 */
@RestController
@CrossOrigin
@RequestMapping("user")
public class WxLoginController {
    @Autowired
    private UserService userService;

    private ResponseDTO<User> responseDTO = null; // 是否用微信登录成功，dto为null，则尚未登录

    /**
     * 微信登录
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("wxlogin")
    public String wxlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 微信官方发给我们一个临时凭证
        String code = request.getParameter("code");
        System.out.println("【临时凭证】code = " + code);
        // 2. 通过code，去微信官方申请一个正式的token（令牌）
        String getTokenByCode_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd99431bbff8305a0&secret=60f78681d063590a469f1b297feff3c4&code=" + code + "&grant_type=authorization_code";
        String tokenString = HttpClientUtil.doGet(getTokenByCode_url);
        System.out.println("tokenString = " + tokenString);
        // 将json格式的token字符串转换成实体对象，方便存和取
        Token token = JSON.parseObject(tokenString, Token.class);

        // 3. 通过token，去微信官方获取用户的信息
        String getUserByToken_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.getAccess_token() + "&openid=" + token.getOpenid();
        String userinfoString = HttpClientUtil.doGet(getUserByToken_url);
        // 将json格式的user字符串转换成实体对象，方便存和取
        WxUser wxUser = JSON.parseObject(userinfoString, WxUser.class);

        // 泡泡的业务流程！ 需要 手机号（wxUser.getUnionid()）和密码（wxUser.getUnionid()）,头像和昵称

        // 检测手机号是否注册

        String phone = wxUser.getUnionid();
        User user1 = userService.selectByPhone(phone);

        responseDTO = new ResponseDTO<>();
        if(user1 == null){
            // 未注册，自动注册并登录
            User user = new User();

            user.setPhone(wxUser.getUnionid());
            user.setPassword(wxUser.getUnionid());
            user.setName(wxUser.getNickname());
            user.setPortrait(wxUser.getHeadimgurl());
            user.setStatus("ENABLE");
            user.setIsDel(0);
            user.setWeixin(1);

            Date date = new Date();
            //Date类型转String  //可指定任意的返回格式  yyyy
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = sdf.format(date);

            user.setCreateTime(dateString);
            user.setUpdateTime(dateString);
            userService.insertUser(user);
            responseDTO.setMessage("手机号尚未注册，系统已帮您自动注册，请牢记密码！");
            user1 = user;
        }else{
            User user2 = userService.selectByPhone(wxUser.getUnionid());
            if(user2.getPassword().equals(wxUser.getUnionid())!=true){
                responseDTO.setState(300); //300表示失败
                responseDTO.setMessage("帐号密码不匹配，登录失败！");
            }else{
                responseDTO.setState(200); //200表示成功
                responseDTO.setMessage("登录成功！");
            }
        }
        responseDTO.setContent(user1);
        response.sendRedirect("http://localhost:8080");
        return null;
    }

    @GetMapping("checkWxStatus")
    public ResponseDTO<User> checkWxStatus(){
        if(responseDTO==null){
            return null;
        }else {
            return this.responseDTO;
        }
    }

    @GetMapping("logout")
    public Object logout(){
        this.responseDTO = null;
        return null;
    }
}
